"""
Tools to work with fasta files and entries

@author:charles.hefer@gmail.com
@notice: No guarentee is given to the accuracy, usefulness or purpose
of any of the tools described and implemented in this package
"""
from Bio import SeqIO
import sys, optparse

def split_to_multiple_entries(handle, target_dir="fasta_entries"):
	"""
	Accepts a file handle to a readable fasta file, and a target directory.
	Steps through the fasta file, and writes every entry to a seperate
	file, named afther the "entry.name" feature of the sequence.
	
	
	@requires: BioPython
	@type handle: A readable file handle
	@var target_dir: The location of the output directory, defaults to fasta_entries
	"""	
	for entry in SeqIO.parse(handle, "fasta"):
		#open the target file
		try: 
			outhandle = open("%s/%s.fasta" % (target_dir, entry.name), "w")
		except Exception, e:
			print(e)
			print("An error occured creating the new fasta files:\n%s" % e)
			raise sys.exit()
		
		SeqIO.write([entry], outhandle, "fasta")
		outhandle.close()


def __main__():
	"""Can also be used as a standalone tool, although not well documented"""
	parser = optparse.OptionParser()
	parser.add_option("-f", "--fasta", default=None, dest="fasta_input",
		help="The fasta file to use as imput")
	parser.add_option("-d","--outdir", default=None, dest="out_dir",
		help="The output directory, output stored here")
	parser.add_option("-t","--function", default=None, dest="function",
		help="The function to call")
	(options, args) = parser.parse_args()
	
	if options.function == "split_to_multiple_entries":
		try:
			split_to_multiple_entries(open(options.fasta_input, "r"), 
										options.out_dir)
		except Exception, e:
			print "An error occurred with '%s':\n%s" % (options.function, e)
			raise sys.exit()
			
	

		
if __name__=="__main__":
	__main__()
			
	
	